import { Component } from '@angular/core';
import {
  FormControl,
  FormGroup,
  Validators,
  AbstractControl,
  ValidationErrors,
} from '@angular/forms';
import { Observable, catchError, map, of } from 'rxjs';
import { checkPwdFn } from 'src/app/request';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss'],
})
export class DemoComponent {
  public colorControl = new FormControl('123');

  public telCustomValidator = (
    control: AbstractControl
  ): ValidationErrors | null => {
    const tel = control.value;
    if (!tel) {
      return { required: true };
    }
    if (tel.length !== 11) {
      return { length: true };
    }
    return null;
  };

  public form = new FormGroup({
    name: new FormControl('', Validators.required),
    tel: new FormControl('xxx-01234567', [this.telCustomValidator]),
  });

  public submit() {
    console.log(this.form);
    if (this.form.invalid) {
      alert('表单校验失败!');
      return;
    }
    console.log('submit!', this.form.value);
  }

  private cunstomValidatePwd = (control: AbstractControl):Observable<ValidationErrors | null> => {
    return checkPwdFn(control.value).pipe(
      map(res=>{
        if(res === 'pass'){
          // 通过远程校验
          return null;
        }
        return {remote: res}
      }),
      catchError(()=>of({remote: 'Network error 密码校验失败！'}))
    )
  }

  private confirmPwdValidator = (
    control: AbstractControl
  ): ValidationErrors | null => {
    const pwd = control.get('pwd')?.value;
    const confirmPwd = control.get('confirmPwd')?.value;
    if (pwd !== confirmPwd) {
      return { 'not-confirm': true };
    }
    return null;
  };

  public pwdForm = new FormGroup(
    {
      pwd: new FormControl('',  {asyncValidators: [this.cunstomValidatePwd],validators: [Validators.required], updateOn :'blur', }),
      confirmPwd: new FormControl('', Validators.required),
    },
    { validators: this.confirmPwdValidator }
  );
}
